import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getNotebooks, getNotebooksTree, createNotebook, updateNotebook, deleteNotebook } from '@/api/notebooks'
import { ElMessage } from 'element-plus'

export const useNotebookStore = defineStore('notebook', () => {
  const notebooks = ref([])
  const notebooksTree = ref([])
  const loading = ref(false)

  // 获取所有笔记本
  async function fetchNotebooks() {
    loading.value = true
    try {
      notebooks.value = await getNotebooks()
    } catch (error) {
      ElMessage.error('获取笔记本列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取笔记本树
  async function fetchNotebooksTree() {
    loading.value = true
    try {
      notebooksTree.value = await getNotebooksTree()
    } catch (error) {
      ElMessage.error('获取笔记本树失败')
    } finally {
      loading.value = false
    }
  }

  // 创建笔记本
  async function addNotebook(notebookData) {
    try {
      const notebook = await createNotebook(notebookData)
      notebooks.value.push(notebook)
      ElMessage.success('笔记本创建成功')
      await fetchNotebooksTree() // 刷新树
      return notebook
    } catch (error) {
      ElMessage.error('创建笔记本失败')
      throw error
    }
  }

  // 更新笔记本
  async function modifyNotebook(id, notebookData) {
    try {
      const notebook = await updateNotebook(id, notebookData)
      const index = notebooks.value.findIndex(n => n.id === id)
      if (index !== -1) {
        notebooks.value[index] = notebook
      }
      ElMessage.success('笔记本更新成功')
      await fetchNotebooksTree() // 刷新树
      return notebook
    } catch (error) {
      ElMessage.error('更新笔记本失败')
      throw error
    }
  }

  // 删除笔记本
  async function removeNotebook(id) {
    try {
      await deleteNotebook(id)
      notebooks.value = notebooks.value.filter(n => n.id !== id)
      ElMessage.success('笔记本已删除')
      await fetchNotebooksTree() // 刷新树
    } catch (error) {
      ElMessage.error('删除笔记本失败')
      throw error
    }
  }

  return {
    notebooks,
    notebooksTree,
    loading,
    fetchNotebooks,
    fetchNotebooksTree,
    addNotebook,
    modifyNotebook,
    removeNotebook
  }
})

